package service;

import gui.ExceptionHandler;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import javax.swing.SwingWorker;

import dao.Dao;
import model.*;

public class StackMonitor extends SwingWorker<Void, Void> {
	private int sleep = 500;
	private boolean active = true;
	private List<Stack> stacksNotified;
	private OutdatedStackMonitor outdatedStackListener; 
	
	public StackMonitor(Observer stackAlertListener) {
		super();
		stacksNotified = new ArrayList<Stack>();
		outdatedStackListener = new OutdatedStackMonitor();
		outdatedStackListener.addObserver(stackAlertListener);
	}
	
	private class OutdatedStackMonitor extends Observable {
		public void monitor() {
			try {		
				while (active) {
					List<Stack> outdatedStacks = Service.getInstance().checkForOutdatedStacks(); 
					if (outdatedStacks != null && outdatedStacks.size() > 0)
						for (Stack stack : outdatedStacks) 
							if (!stacksNotified.contains(stack)) { 
								stacksNotified.add(stack);
								setChanged();
								notifyObservers(stack);
							}
					
					//updateView
					setChanged();
					notifyObservers();
					Thread.sleep(sleep);
				}
				
				while (!active) 
					Thread.sleep(sleep);
			} catch (Exception e) {
				ExceptionHandler.handleException(e);
			} finally {
				monitor();
			}
		}
	}
	
	@Override
	protected Void doInBackground() throws Exception {
		System.out.println("Stack monitor started");
		outdatedStackListener.monitor();
		
		return null;
	}

	public int getSleep() {
		return sleep;
	}

	public void setSleep(int sleep) {
		this.sleep = sleep;
	}

	public boolean isActive() {
		return active;
	}

	public void setActive(boolean active) {
		this.active = active;
	}
}
